/*!
 * v2gogo-vue-js-sdk v0.10
 *
 * Copyright 2017 by WJZP
 * Created by yangzhen
 *
 * Date: 2018-10-25
*/
import wx from 'weixin-js-sdk'
const apiPrefix = 'https://test-api.v2gogo.com';
const imgPrefix = 'http://test-images.v2gogo.com/';
const videoPrefix = 'http://test-images.v2gogo.com/';

/**
 * js调用原生交互
 引用说明  window.jsbrige.callNative(<方法名>,<参数>,<返回值回掉函数>)；
 //
 window.jsbrige.callNative('getSAPrepareAttribute',"",function(data){
  alert(data);
})
 }
 *
 */
function JSBrige( ){
  window.funcMap = new Map();
  this.callNative =  function (nativeMethodName,argument, callback ){
    let argumentTmp = argument;
    if (typeof nativeMethodName !== 'string') {
        throw new Error('Type of method must be string');
    }

    //Allowed types are Number, String, Date, Array,Object, and Null
    let type = typeof argument;
    let fliter = ["string","number","object","null"];
    if (fliter.indexOf(type) === -1) {
        throw new Error('Type of argument must be number,string,object,and null');
    }

    if (type === "object") {
        argumentTmp = JSON.stringify(argument);
    }
    let call_id = nativeMethodName + Date.parse(new Date());
    if(callback != null && callback !== undefined){
        funcMap[call_id] = callback;
    }

    if (window.v2ggAndroidNativeMethod !== undefined) {
        window.v2ggAndroidNativeMethod.postMessage(nativeMethodName,argumentTmp,call_id);
    } else {
        if (eval(`window.webkit.messageHandlers.${nativeMethodName}`) !== undefined) {
            let prames = {
                _call_id:call_id,
                argument:argument
            }
            let pramesTmp = JSON.stringify(prames); 
            return eval(`window.webkit.messageHandlers.${nativeMethodName}.postMessage(${pramesTmp})`);
        }
        else {
            throw new Error('Not in native environment');
        }
    }
  }

  /**
   *  callId 调用原生参数能取到
   */
  this.iosCallback = function (callId, params)
  {
      let callback = funcMap[callId];
      //method(params);
      if(callback != null && callback !== undefined){
          callback(params);
      }
      funcMap.delete(callId);
  }
}
window.jsbrige = new JSBrige();

export default {
  apiPrefix,
  imgPrefix,
  videoPrefix,
  jsbrige,
  /**
   * 判断是否在APP内
   * @return {boolean}
   */
  isV2gogoApp: function () {
    return navigator.userAgent.indexOf("v2ggapp") > -1;
  },
  isWeiXin: function() {        // 判断是否在微信客户端内
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
  },
  isQQ: function() {
    var ua = window.navigator.userAgent.toLowerCase();
    if((ua.match(/QQ/i) == 'qq') || (ua.match(/MQQ/i) == 'mqq')){
      return true;
    }else{
      return false;
    }
  },
  isAndroid: function () {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/android/i) == 'android') {
      return true;
    } else {
      return false;
    }
  },
  isIos: function () {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/ios/i) == 'ios') {
      return true;
    } else {
      return false;
    }
  },
  isPc: function() {
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/Android|webOS|iPhone|iPod|BlackBerry/i)) {
      return false;
    } 
    else {
      return true;
    }
  },
  isMiniProgram: function() {
    return window.__wxjs_environment === 'miniprogram';
    // return true;      // 本地调试用
  },
  getUserId: function () {
    var v2gogoappJson, userId, r, re, tmp;
    v2gogoappJson = JSON.parse(window.sessionStorage.getItem("v2gogoappJson"));
    if (v2gogoappJson === null) {
        var ua = window.navigator.userAgent;
        re = new RegExp("v2ggapp(.*)");
        r = ua.match(re);
        if (r != null) {
          re = new RegExp("{.*}");
          tmp = r[1].match(re);
          window.sessionStorage.setItem("v2gogoappJson", tmp[0]);
          userId = JSON.parse(tmp[0]).user.id;
        }
        else {
            userId = null;
        }
    }
    else {
        userId = v2gogoappJson.user.id;
    }
    return userId;
  },
  getUserName: function () {
    var v2gogoappJson, username, r, re, temp;
    v2gogoappJson = JSON.parse(window.sessionStorage.getItem("v2gogoappJson"));
    if (v2gogoappJson === null) {
        var ua = window.navigator.userAgent;
        re = new RegExp("v2ggapp(.*)");
        r = ua.match(re);
        if (r != null) {
          re = new RegExp("{.*}");
          tmp = r[1].match(re);
          window.sessionStorage.setItem("v2gogoappJson", tmp[0]);
          username = JSON.parse(tmp[0]).user.phone;
        }
        else {
            username = null;
        }
    }
    else {
        username = v2gogoappJson.user.phone;
    }
    return username;
  },
  getUrlParam: function(key) {
    var r, re;
    re = new RegExp("[?|&]" + key + "=(.*?)(&|$)(#?)");     // 兼容带有“＃login”的url地址
    r = window.location.href.match(re);
    if (r != null) return decodeURIComponent(r[1]);
    return null;
  },
  /**
   * 获得url中参数值
   * @param name  参数名
   * @param url   可为null 可以指定url
   * @returns {null}
   */
  getQueryString: function(name, url) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var url = url ? url : window.location.search.substr(1);
    var r = url.match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
  },
  /**
   * 初始化分享按钮
   * @param {Object} shareInfo
   * @vue {Object} vue vue实例
   * example: var shareInfo = {
              title : "直播：" + liveStudio.title,
              desc : liveStudio.description,
              imgUrl : imagesPrefix + liveStudio.thumbnail + "?imageView2/2/w/300",
              url : window.location.href
          };
   */
  initAppShareBtn: function (shareInfo, vue) {
    if (this.isV2gogoApp() === true) {
      window.jsbrige.callNative('onShareInfo', shareInfo, function(data){});
    }
    else if (this.isWeiXin()) {
      this.wxConfig(shareInfo, vue);
    }
  },
  /**
   * formate timastamp to time
   * @param {String} timestamp
   */
  formatDate: function (timestamp){
    var now = new Date(parseInt(timestamp));
    var year=now.getFullYear();
    var month=now.getMonth()+1;
    var date=now.getDate();
    var hour=now.getHours();
    var minute=now.getMinutes();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (date >= 0 && date <= 9) {
      date = "0" + date;
    }
    if (hour >= 0 && hour <= 9) {
      hour = "0" + hour;
    }
    if (minute >= 0 && minute <= 9) {
      minute = "0" + minute;
    }
    return year+"-"+month+"-"+date+" "+hour+":"+minute;
  },
  /**
   * 申请使用微信JS接口
   * @param shareInfo
   * @vue {Object} vue vue实例
   */
  wxConfig: function (shareInfo, vue) {
    var _this = this;
    vue.$http.get('/common/wxConfig', {params: {url: window.location.href}}).then(function (response) {
      if (response.body.code === 0) {
        var data = response.body.result;
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: data.appId, // 必填，公众号的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的时间戳
          nonceStr: data.nonceStr, // 必填，生成签名的随机串
          signature: data.signature,// 必填，签名，见附录1
          jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        _this.wxReady(shareInfo);
      }
    });
  },
  /**
   * 微信对象已准备好时，初始化右上角分享按钮（分享给朋友，分享到朋友圈）
   * @param shareInfo
   */
  wxReady: function (shareInfo) {
    wx.ready(function () {
      wx.onMenuShareTimeline({      // 分享到朋友圈
        title: shareInfo.title,
        link: shareInfo.url, // 分享链接
        imgUrl: shareInfo.imgUrl, // 分享图标
        success: function () {
            // 用户确认分享后执行的回调函数
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        },
        fail: function (res) {}
      });
      wx.onMenuShareAppMessage({    // 分享给朋友
        title: shareInfo.title,
        link: shareInfo.url, // 分享链接
        imgUrl: shareInfo.imgUrl, // 分享图标
        desc: shareInfo.desc,
        type: 'link', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function () {
            // 用户确认分享后执行的回调函数
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        }
      });
    });
  },
  addCookie: function(name, value, expireHours) {
    var cookieString = name + "=" + escape(value) + "; path=/";
    //判断是否设置过期时间
    if (expireHours > 0) {
      var date = new Date();
      date.setTime(date.getTime() + expireHours * 3600 * 1000);
      cookieString = cookieString + "; expires=" + date.toUTCString();
    }
    //默认的cookie时间1个月 业务需求
    if (typeof(expireHours) == 'undefined') {
      var date = new Date();
      date.setTime(date.getTime() + 24 * 30 * 3600 * 1000);
      cookieString = cookieString + "; expires=" + date.toUTCString();
    }
    document.cookie = cookieString;
  },
  getCookie: function (name) {
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");
    for (var i = 0; i < arrcookie.length; i++) {
      var arr = arrcookie[i].split("=");
      if (arr[0] == name) return arr[1];
    }
    return "";
  },
  /**
   * formate timastamp to time
   * @param {String} timestamp
   */
  formatTimestamp: function(timestamp, format) {
    var now = new Date(parseInt(timestamp));
    var date = {
      "M+": now.getMonth() + 1,
      "d+": now.getDate(),
      "h+": now.getHours(),
      "m+": now.getMinutes(),
      "s+": now.getSeconds(),
      "q+": Math.floor((now.getMonth() + 3) / 3),
      "S+": now.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (now.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1
          ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
      }
    }
    return format;
  }
}
